<template>
  <div class="post-detail-container">

        <!-- 返回按钮 -->
    <div class="back-button-container">
      <button class="btn btn-back" @click="goBack">
        <i class="fas fa-arrow-left me-2"></i>返回上一页
      </button>
    </div>

    <div class="container py-4">
      <!-- 错误提示 -->
      <div v-if="error" class="alert alert-danger" role="alert">
        <h4 class="alert-heading">加载失败!</h4>
        <p>{{ error }}</p>
        <hr>
        <button class="btn btn-outline-danger" @click="fetchPost">重新加载</button>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="loading" class="d-flex justify-content-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <span class="ms-2">正在加载帖子详情...</span>
      </div>

      <!-- 主要内容 -->
      <div v-else class="row">
        <!-- 左侧帖子内容区域 -->
        <div class="col-lg-8">
          <div class="card post-content-card shadow-sm mb-4">
            <div class="card-body">
              <!-- 帖子标题 -->
              <h1 class="post-title mb-3">{{ post.title }}</h1>
              
              <!-- 帖子元信息 -->
              <div class="post-meta d-flex align-items-center mb-4">
                <div class="user-avatar me-3">
                  <div v-if="avatarLoadingStates[post.authorAvatar]" class="d-flex align-items-center justify-content-center rounded-circle bg-light" style="width: 40px; height: 40px;">
                    <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                  </div>
                  <img 
                    v-else-if="post.authorAvatar"
                    :src="post.authorAvatar" 
                    :alt="post.authorName" 
                    class="rounded-circle" 
                    width="40" 
                    height="40" 
                    @error="handleAvatarError"
                    @load="() => handleAvatarLoad(post.authorAvatar)"
                  >
                  <img 
                    v-else
                    src="@/assets/images/头像加载失败.jpg" 
                    :alt="post.authorName" 
                    class="rounded-circle" 
                    width="40" 
                    height="40"
                  >
                </div>
                <div class="user-info flex-grow-1">
                  <div class="d-flex align-items-center">
                    <h5 class="mb-0 me-2">{{ post.authorName || '匿名用户' }}</h5>
                    <span class="badge bg-primary">{{ post.authorRole || '用户' }}</span>
                  </div>
                  <div class="text-muted small">
                    <span class="me-3">{{ formatDate(post.createdAt) }}</span>
                    <span class="me-3"><i class="bi bi-eye me-1"></i>{{ post.viewCount || 0 }} 浏览</span>
                    <span><i class="bi bi-chat me-1"></i>{{ totalCommentsCount }} 评论</span>
                  </div>
                </div>
                <div class="post-status">
                  <span class="badge" :class="getStatusBadgeClass(post.status)">{{ getStatusText(post.status) }}</span>
                </div>
              </div>

              <!-- 帖子图片轮播 -->
              <div v-if="postImages.length > 0" class="post-image-carousel mb-4">
                <div id="postImageCarousel" class="carousel slide" data-bs-ride="carousel">
                  <div class="carousel-indicators">
                    <button 
                      v-for="(image, index) in postImages" 
                      :key="index"
                      type="button" 
                      data-bs-target="#postImageCarousel" 
                      :data-bs-slide-to="index"
                      :class="{ active: index === 0 }"
                      :aria-label="`Slide ${index + 1}`"
                    ></button>
                  </div>
                  <div class="carousel-inner">
                    <div 
                      v-for="(image, index) in postImages" 
                      :key="index"
                      class="carousel-item"
                      :class="{ active: index === 0 }"
                    >
                      <div v-if="imageLoadingStates[image.imageUrl]" class="d-flex align-items-center justify-content-center" style="height: 400px;">
                        <div class="spinner-border text-primary" role="status">
                          <span class="visually-hidden">加载中...</span>
                        </div>
                      </div>
                      <img 
                        v-else
                        :src="image.imageUrl.startsWith('http') ? image.imageUrl : 'http://localhost:8080' + image.imageUrl" 
                        :alt="`图片 ${index + 1}`"
                        class="d-block w-100 rounded"
                        @error="handleImageError(image.imageUrl)"
                        @load="handleImageLoad(image.imageUrl)"
                        @click="openImageModal(image.imageUrl, index)"
                        style="height: 400px; object-fit: cover; cursor: pointer;"
                      >
                    </div>
                  </div>
                  <button v-if="postImages.length > 1" class="carousel-control-prev custom-carousel-control" type="button" data-bs-target="#postImageCarousel" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon custom-carousel-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">Previous</span>
                  </button>
                  <button v-if="postImages.length > 1" class="carousel-control-next custom-carousel-control" type="button" data-bs-target="#postImageCarousel" data-bs-slide="next">
                    <span class="carousel-control-next-icon custom-carousel-icon" aria-hidden="true"></span>
                    <span class="visually-hidden">Next</span>
                  </button>
                </div>
              </div>
              <div v-else class="post-cover mb-4">
                <img src="@/assets/images/封面加载失败.webp" alt="默认封面" class="img-fluid rounded">
              </div>

              <!-- 帖子价格和分类 -->
              <div class="post-info d-flex justify-content-between align-items-center mb-4 p-3 bg-light rounded">
                <div class="post-price">
                  <span v-if="post.price" class="h4 text-success mb-0">¥{{ post.price }}</span>
                  <span v-else class="h4 text-success mb-0">面议</span>
                </div>
                <div class="post-category">
                  <span class="badge bg-secondary fs-6">{{ categoryName }}</span>
                </div>
              </div>

              <!-- 帖子内容 -->
              <div class="post-body mb-4">
                <div class="content" v-html="post.content"></div>
              </div>

              <!-- 帖子操作按钮 -->
              <div class="post-actions d-flex justify-content-between align-items-center mb-4">
                <div class="action-buttons">
                  <button class="btn btn-outline-primary me-2" @click="toggleLike">
                    <i class="bi" :class="post.isLiked ? 'bi-heart-fill text-danger' : 'bi-heart'"></i>
                    {{ post.isLiked ? '已点赞' : '点赞' }} ({{ post.likeCount || 0 }})
                  </button>
                  <button class="btn btn-outline-primary me-2" @click="toggleFavorite">
                    <i class="bi" :class="post.isFavorited ? 'bi-star-fill text-warning' : 'bi-star'"></i>
                    {{ post.isFavorited ? '已收藏' : '收藏' }} ({{ post.favoriteCount || 0 }})
                  </button>
                  <button class="btn btn-outline-primary" @click="scrollToComments">
                    <i class="bi bi-chat-left-text"></i> 评论
                  </button>
                </div>
                <div class="share-buttons">
                  <button class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-share"></i> 分享
                  </button>
                </div>
              </div>

              <!-- 评论区 -->
              <div class="comments-section" id="comments">
                <h5 class="mb-3">评论 ({{ totalCommentsCount }})</h5>
                
                <!-- 评论输入框 -->
                <div class="comment-form mb-4">
                  <div class="d-flex">
                    <div class="user-avatar me-3">
                      <div v-if="avatarLoadingStates[currentUser.avatar]" class="d-flex align-items-center justify-content-center rounded-circle bg-light" style="width: 40px; height: 40px;">
                        <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                      </div>
                      <img 
                        v-else-if="currentUser.avatar"
                        :src="currentUser.avatar" 
                        :alt="currentUser.nickname" 
                        class="rounded-circle" 
                        width="40" 
                        height="40" 
                        @error="handleAvatarError"
                        @load="() => handleAvatarLoad(currentUser.avatar)"
                      >
                      <img 
                        v-else
                        src="@/assets/images/头像加载失败.jpg" 
                        :alt="currentUser.nickname" 
                        class="rounded-circle" 
                        width="40" 
                        height="40"
                      >
                    </div>
                    <div class="flex-grow-1">
                      <textarea v-model="newComment" class="form-control" rows="3" placeholder="写下你的评论..."></textarea>
                      <div class="d-flex justify-content-between align-items-center mt-2">
                        <div v-if="replyToCommentId" class="text-muted small">
                          <span>回复评论 #{{ replyToCommentId }}</span>
                          <button class="btn btn-sm btn-link p-0 ms-2" @click="cancelReply">取消回复</button>
                        </div>
                        <div v-else class="text-muted small">
                          还可以输入 {{ 500 - newComment.length }} 字
                        </div>
                        <button class="btn btn-primary" @click="addComment" :disabled="!newComment.trim()">发表评论</button>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 评论列表 -->
                <div class="comments-list">
                  <div v-for="comment in comments" :key="comment.id" class="comment-item mb-4 pb-3 border-bottom">
                    <div class="d-flex">
                      <div class="user-avatar me-3">
                        <div v-if="avatarLoadingStates[comment.userAvatar]" class="d-flex align-items-center justify-content-center rounded-circle bg-light" style="width: 40px; height: 40px;">
                          <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                        </div>
                        <img 
                          v-else-if="comment.userAvatar"
                          :src="comment.userAvatar" 
                          :alt="comment.userName" 
                          class="rounded-circle" 
                          width="40" 
                          height="40" 
                          @error="handleAvatarError"
                          @load="() => handleAvatarLoad(comment.userAvatar)"
                        >
                        <img 
                          v-else
                          src="@/assets/images/头像加载失败.jpg" 
                          :alt="comment.userName" 
                          class="rounded-circle" 
                          width="40" 
                          height="40"
                        >
                      </div>
                      <div class="flex-grow-1">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                          <h6 class="mb-0">{{ comment.userName || '匿名用户' }}</h6>
                          <span class="text-muted small">{{ formatRelativeTime(comment.createdAt) }}</span>
                        </div>
                        <p class="mb-2">{{ comment.content }}</p>
                        <div class="comment-actions">
                          <button class="btn btn-sm btn-outline-secondary me-2" @click="toggleCommentLike(comment)">
                            <i class="bi" :class="comment.isLiked ? 'bi-heart-fill text-danger' : 'bi-heart text-secondary'"></i>
                            {{ comment.likeCount || 0 }}
                          </button>
                          <button class="btn btn-sm btn-outline-secondary me-2" @click="replyToComment(comment)">
                            回复
                          </button>
                          <button 
                            v-if="comment.userId === currentUser.id" 
                            class="btn btn-sm btn-outline-danger" 
                            @click="deleteComment(comment)">
                            删除
                          </button>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 子评论展开按钮 -->
                    <div v-if="comment.replies && comment.replies.length > 0" class="replies-toggle mt-2">
                      <button 
                        class="btn btn-sm btn-link p-0 text-decoration-none" 
                        @click="comment.showReplies = !comment.showReplies"
                      >
                        {{ comment.showReplies ? '收起回复' : `查看 ${comment.replies.length} 条回复` }}
                        <i class="bi" :class="comment.showReplies ? 'bi-chevron-up' : 'bi-chevron-down'"></i>
                      </button>
                    </div>
                    
                    <!-- 子评论 -->
                    <div v-show="comment.showReplies" class="replies ms-5 mt-3">
                      <div v-for="reply in comment.replies" :key="reply.id" class="reply-item mb-3">
                        <div class="d-flex">
                          <div class="user-avatar me-2">
                            <div v-if="avatarLoadingStates[reply.userAvatar]" class="d-flex align-items-center justify-content-center rounded-circle bg-light" style="width: 30px; height: 30px;">
                              <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                            </div>
                            <img 
                              v-else-if="reply.userAvatar"
                              :src="reply.userAvatar" 
                              :alt="reply.userName" 
                              class="rounded-circle" 
                              width="30" 
                              height="30" 
                              @error="handleAvatarError"
                              @load="() => handleAvatarLoad(reply.userAvatar)"
                            >
                            <img 
                              v-else
                              src="@/assets/images/头像加载失败.jpg" 
                              :alt="reply.userName" 
                              class="rounded-circle" 
                              width="30" 
                              height="30"
                            >
                          </div>
                          <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                              <h6 class="mb-0 small">{{ reply.userName || '匿名用户' }}</h6>
                              <span class="text-muted small">{{ formatRelativeTime(reply.createdAt) }}</span>
                            </div>
                            <p class="mb-1 small">{{ reply.content }}</p>
                            <div class="comment-actions">
                              <button class="btn btn-sm btn-outline-secondary me-2" @click="toggleCommentLike(reply)">
                                <i class="bi" :class="reply.isLiked ? 'bi-heart-fill text-danger' : 'bi-heart text-secondary'"></i>
                                {{ reply.likeCount || 0 }}
                              </button>
                              <button class="btn btn-sm btn-outline-secondary me-2" @click="replyToComment(reply)">
                                回复
                              </button>
                              <button 
                                v-if="reply.userId === currentUser.id" 
                                class="btn btn-sm btn-outline-danger" 
                                @click="deleteComment(reply)">
                                删除
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="col-lg-4">
          <!-- 作者信息卡片 -->
          <div class="card author-card shadow-sm mb-4">
            <div class="card-header bg-primary text-white">
              <h5 class="mb-0">作者信息</h5>
            </div>
            <div class="card-body text-center">
              <div class="author-avatar mb-3">
                <div v-if="avatarLoadingStates[post.authorAvatar]" class="d-flex align-items-center justify-content-center rounded-circle bg-light" style="width: 80px; height: 80px;">
                  <div class="spinner-border text-primary" role="status"></div>
                </div>
                <img 
                  v-else-if="post.authorAvatar"
                  :src="post.authorAvatar" 
                  :alt="post.authorName" 
                  class="rounded-circle avatar-image" 
                  width="80" 
                  height="80" 
                  @error="handleAvatarError"
                  @load="() => handleAvatarLoad(post.authorAvatar)"
                  @click="$router.push(`/user/Detail/${post.userId}`)"
                >
                <img 
                  v-else
                  src="@/assets/images/头像加载失败.jpg" 
                  :alt="post.authorName" 
                  @click="$router.push(`/user/Detail/${post.userId}`)"
                  class="rounded-circle avatar-image" 
                  width="80" 
                  height="80"
                >
              </div>
              <h5 class="author-name">{{ post.authorName || '匿名用户' }}</h5>
              <p class="text-muted mb-3">{{ post.authorBio || '这个用户很懒，什么都没留下' }}</p>
              <div class="author-stats d-flex justify-content-around mb-3">
                <div class="stat-item">
                  <div class="stat-value">{{ post.authorPostCount || 0 }}</div>
                  <div class="stat-label">帖子</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ post.authorFollowerCount || 0 }}</div>
                  <div class="stat-label">粉丝</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ post.authorFollowingCount || 0 }}</div>
                  <div class="stat-label">关注</div>
                </div>
              </div>
              <button class="btn btn-outline-primary w-100" @click="followAuthor" :disabled="followLoading">
                <span v-if="followLoading" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                {{ post.authorIsFollowed ? '已关注' : '关注' }}
              </button>
            </div>
          </div>

          <!-- 热门推荐 -->
          <div class="card recommended-posts-card shadow-sm">
            <div class="card-header">
              <h5 class="mb-0">热门推荐</h5>
            </div>
            <div class="card-body">
              <div v-for="recommendedPost in HotRecommendedPosts" :key="recommendedPost.id" 
                   class="recommended-post-item d-flex mb-3 pb-3 border-bottom">
                <div class="post-thumb me-3">
                  <div v-if="imageLoadingStates[recommendedPost.coverImage]" class="d-flex align-items-center justify-content-center rounded bg-light" style="width: 60px; height: 60px;">
                    <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                  </div>
                  <img 
                    v-else-if="recommendedPost.coverImage"
                    :src="recommendedPost.coverImage" 
                    :alt="recommendedPost.title" 
                    class="rounded" 
                    width="60" 
                    height="60" 
                    @error="handleImageError(recommendedPost.coverImage)"
                    @load="handleImageLoad(recommendedPost.coverImage)"
                  >
                  <img 
                    v-else
                    src="@/assets/images/封面加载失败.webp" 
                    :alt="recommendedPost.title" 
                    class="rounded" 
                    width="60" 
                    height="60"
                  >
                </div>
                <div class="post-info flex-grow-1">
                  <h6 class="post-title mb-1">
                    <router-link :to="`/post/detail/${recommendedPost.id}`" class="text-decoration-none">{{ recommendedPost.title }}</router-link>
                  </h6>
                  <div class="post-meta text-muted small">
                    <span v-if="recommendedPost.price" class="me-2">¥{{ recommendedPost.price }}</span>
                    <span v-else class="me-2">面议</span>
                    <span><i class="bi bi-eye me-1"></i>浏览量：{{ recommendedPost.viewCount || 0 }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片放大查看器 -->
    <div v-if="showImageModal" class="image-modal" @click="closeImageModal">
      <span class="image-modal-close" @click.stop="closeImageModal">&times;</span>
      <!-- 左侧切换按钮 -->
      <div v-if="currentImageIndex > 0" class="image-modal-nav image-modal-nav-prev" @click.stop="prevImage">
        <i class="bi bi-chevron-left"></i>
      </div>
      <!-- 右侧切换按钮 -->
      <div v-if="currentImageIndex < postImages.length - 1" class="image-modal-nav image-modal-nav-next" @click.stop="nextImage">
        <i class="bi bi-chevron-right"></i>
      </div>
      <div class="image-modal-content" @click.stop>
        <img :src="currentImageSrc" alt="放大图片" class="image-modal-image">
      </div>
      <div class="image-modal-caption">{{ currentImageIndex + 1 }} / {{ postImages.length }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {  getPostDetailService, 
          getCategoriesListService, 
          getPostCoverService,
          getHotPostsService } from '@/api/post.js'

import {  getUserPostCountService,
          getUserInfoByIdService,
        } from '@/api/user.js'

import { getPostLikeCountService,
          getPostFavoriteCountService,
          addLikeService,
          addFavoriteService,
          removeLikeService,
          removeFavoriteService,
          getLikesIdService,
        } from '@/api/LikesFavorites.js'

import { FollowService,
          UnfollowService,
          getFollowingListService,
          getFollowerListService
       } from '@/api/Follow.js'

import { getPostCommentsService, 
         addCommentService,
         deleteCommentService,
         likeCommentService,
         checkCommentsLikeStatusService } from '@/api/comments.js'

import useUserInfoStore from '@/stores/userInfo.js'
import defaultAvatar from '@/assets/images/头像加载失败.jpg'

const route = useRoute()
const router = useRouter()

// 当前用户信息
const currentUser = ref({})

// 帖子数据
const post = ref({})

// 帖子分类数据
const categories = ref([])

// 帖子图片数据
const postImages = ref([])

// 分类名称
const categoryName = ref('')

// 加载状态
const loading = ref(true)

// 错误信息
const error = ref(null)

// 关注按钮加载状态
const followLoading = ref(false)

// 图片加载状态
const imageLoadingStates = ref({})

// 头像加载状态
const avatarLoadingStates = ref({})

// 热门推荐帖子数据
const HotRecommendedPosts = ref([])

// 图片放大查看器相关数据
const showImageModal = ref(false)
const currentImageSrc = ref('')
const currentImageIndex = ref(0)

// 评论相关数据
const comments = ref([])//评论列表
const newComment = ref('')//新增的评论
const replyToCommentId = ref(null) // 用于记录要回复的评论ID

// 返回上一页方法
const goBack = () => {
  router.go(-1)
}

// 计算所有评论数量（包括顶级评论和子评论）
const totalCommentsCount = computed(() => {
  let count = comments.value.length; // 顶级评论数量
  comments.value.forEach(comment => {
    if (comment.replies && Array.isArray(comment.replies)) {
      count += comment.replies.length; // 加上子评论数量
    }
  });
  return count;
});

// 获取当前登录用户信息
const userInfoStore = useUserInfoStore() 
currentUser.value = userInfoStore.info
console.log('currentUser:', currentUser.value)

// 获取帖子详情
const fetchPost = async () => {
  try {
    loading.value = true
    error.value = null
    
    const id = route.params.id
    
    const res = await getPostDetailService(id)
    post.value = res.data
    console.log('获取到的帖子数据:', post.value)
    
    // 根据帖子中的userId获取用户信息
    if (post.value.userId) {
      // console.log('帖子作者ID:', post.value.userId)
      try {
        const userRes = await getUserInfoByIdService(post.value.userId)//获取帖子用户信息
        // console.log('作者信息:', userRes)
        const authorPC =  await getUserPostCountService(userRes.data.id)//获取用户帖子数量
        // 如果成功获取到用户信息，更新帖子的作者信息
        if (userRes.data && userRes.data.id === post.value.userId) {
          post.value.authorName = userRes.data.nickname || userRes.data.username
          post.value.authorAvatar = userRes.data.userPic
          post.value.authorBio = userRes.data.bio
          post.value.authorPostCount = authorPC.data
          
          // 获取作者的关注数和粉丝数
          try {
            const followingRes = await getFollowingListService(userRes.data.id)
            const followerRes = await getFollowerListService(userRes.data.id)
            post.value.authorFollowingCount = followingRes.data.length
            post.value.authorFollowerCount = followerRes.data.length
            // console.log('作者关注数:', post.value.authorFollowingCount, '粉丝数:', post.value.authorFollowerCount)
            
            // 检查当前用户是否已关注该作者
            if (currentUser.value && currentUser.value.id) {
              // console.log('当前用户ID:', currentUser.value.id)
              try {
                const currentUserFollowingRes = await getFollowingListService(currentUser.value.id)
                // console.log('当前用户关注列表:', currentUserFollowingRes)
                const followingList = currentUserFollowingRes.data || []
                
                // 使用专门的函数检查关注状态
                post.value.authorIsFollowed = checkIfFollowing(followingList, post.value.userId)
                // console.log('是否已关注作者:', post.value.authorIsFollowed, '作者ID:', post.value.userId)
              } catch (checkFollowError) {
                console.warn('检查关注状态失败:', checkFollowError)
                console.error('检查关注状态错误详情:', {
                  message: checkFollowError.message,
                  response: checkFollowError.response,
                  status: checkFollowError.response?.status,
                  data: checkFollowError.response?.data
                })
                post.value.authorIsFollowed = false
              }
            } else {
              // 如果没有登录用户，设为未关注
              console.log('用户未登录，设置为未关注状态')
              post.value.authorIsFollowed = false
            }
          } catch (followError) {
            console.warn('获取用户关注/粉丝信息失败:', followError)
            post.value.authorFollowingCount = 0
            post.value.authorFollowerCount = 0
            post.value.authorIsFollowed = false
          }
        }
      } catch (userError) {
        console.warn('获取用户信息失败:', userError)
      }
    }
    
    // 获取分类名称
    await fetchCategories()
    const category = categories.value.find(cat => cat.id === post.value.categoryId)
    if (category) {
      categoryName.value = category.name
    } else {
      categoryName.value = '未知分类'
    }
    
    // 获取帖子图片
    await fetchPostImages(id)

    // 获取帖子点赞，收藏总数
    getPostLikeCountService(post.value.id).then(response => {
      post.value.likeCount = response.data
    })
    getPostFavoriteCountService(post.value.id).then(response => {
      post.value.favoriteCount = response.data
    })
    
    // 获取当前用户对该帖子的点赞和收藏状态
    if (currentUser.value && currentUser.value.id) {
      const { likeId, favoriteId } = await getLikesId(currentUser.value.id, id);
      post.value.isLiked = !!likeId;
      post.value.isFavorited = !!favoriteId;
    }

    // 获取帖子评论
    await fetchComments(id)

  } catch (err) {
    console.error('获取帖子详情失败:', err)
    error.value = `获取帖子详情失败: ${err.message || '未知错误'}`
    ElMessage.error('获取帖子详情失败')
  } finally {
    loading.value = false
  }

  
}
    
// 获取帖子分类
const fetchCategories = async () => {
  try {
    const res = await getCategoriesListService()
    categories.value = res.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取帖子图片
const fetchPostImages = async (postId) => {
  try {
    const res = await getPostCoverService()
    // 过滤出当前帖子的图片
    postImages.value = res.data.filter(img => img.postId === parseInt(postId))
    // console.log('获取到的帖子图片:', postImages.value)
  } catch (error) {
    console.error('获取帖子图片失败:', error)
    ElMessage.error('获取帖子图片失败')
  }
}

// 获取帖子评论
const fetchComments = async (postId) => {
  try {
    const res = await getPostCommentsService(postId)//获取评论
    console.log('获取到的帖子评论:', res.data)
    
    // 处理评论数据，将顶级评论和回复分开
    const topLevelComments = res.data.filter(comment => comment.parentId === 0 || comment.parentId === null)
    const replies = res.data.filter(comment => comment.parentId !== 0 && comment.parentId !== null)
    
    // 获取所有涉及的用户ID
    const userIds = [...new Set(res.data.map(comment => comment.userId).filter(id => id))]
    const userMap = {}
    
    // 批量获取用户信息
    if (userIds.length > 0) {
      for (const userId of userIds) {
        try {
          const userRes = await getUserInfoByIdService(userId)
          userMap[userId] = userRes.data
        } catch (error) {
          console.warn(`获取用户 ${userId} 信息失败:`, error)
        }
      }
    }
    
    // 如果用户已登录，获取用户对这些评论的点赞状态
    let userLikesMap = {}
    if (currentUser.value && currentUser.value.id) {
      try {
        // 收集所有评论ID
        const allCommentIds = [...topLevelComments, ...replies].map(comment => comment.id)
        if (allCommentIds.length > 0) {
          const likeStatusRes = await checkCommentsLikeStatusService(allCommentIds, currentUser.value.id)
          userLikesMap = likeStatusRes.data || {}
        }
      } catch (error) {
        console.warn('获取用户点赞状态失败:', error)
      }
    }
    
    // 将回复添加到对应的顶级评论中
    topLevelComments.forEach(comment => {
      comment.replies = replies.filter(reply => reply.parentId === comment.id)
      // 确保每个评论都有likeCount属性
      comment.likeCount = comment.likeCount || 0
      // 通过userId获取用户信息
      const userInfo = userMap[comment.userId]
      if (userInfo) {
        comment.userName = userInfo.nickname || userInfo.username || '匿名用户'
        comment.userAvatar = userInfo.userPic || userInfo.avatar || ''
      } else {
        comment.userName = '匿名用户'
        comment.userAvatar = ''
      }
      
      // 设置点赞状态（如果用户已登录）
      if (currentUser.value && currentUser.value.id) {
        comment.isLiked = userLikesMap[comment.id] || false
      } else {
        comment.isLiked = false
      }
      
      // 默认不显示回复
      comment.showReplies = false
    })
    
    // 对回复也进行同样处理
    replies.forEach(reply => {
      reply.likeCount = reply.likeCount || 0
      // 通过userId获取用户信息
      const userInfo = userMap[reply.userId]
      if (userInfo) {
        reply.userName = userInfo.nickname || userInfo.username || '匿名用户'
        reply.userAvatar = userInfo.userPic || userInfo.avatar || ''
      } else {
        reply.userName = '匿名用户'
        reply.userAvatar = ''
      }
      
      // 设置点赞状态（如果用户已登录）
      if (currentUser.value && currentUser.value.id) {
        reply.isLiked = userLikesMap[reply.id] || false
      } else {
        reply.isLiked = false
      }
    })
    comments.value = topLevelComments

  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  }
}

// 获取热门推荐帖子
const fetchRecommendedPosts = async () => {
  try {
    const res = await getHotPostsService()
    // 取前5个帖子作为推荐
    let hotPosts = res.data.slice(0, 5)
    
    // 获取帖子封面图片
    let coverImagesRes = null
    try {
      coverImagesRes = await getPostCoverService()
    } catch (error) {
      console.error('获取封面图片失败:', error)
    }
    
    // 处理每个帖子的封面图片
    hotPosts = hotPosts.map(post => {
      let coverImage = null
      if (coverImagesRes && coverImagesRes.data) {
        // 根据post_id查找对应的图片
        const postImages = coverImagesRes.data.filter(img => img.postId === post.id)
        if (postImages.length > 0) {
          const firstImage = postImages[0]
          coverImage = firstImage.imageUrl.startsWith('http') 
            ? firstImage.imageUrl 
            : `http://localhost:8080${firstImage.imageUrl}`
        }
      }
      
      return {
        ...post,
        coverImage: coverImage
      }
    })
    
    HotRecommendedPosts.value = hotPosts
  } catch (error) {
    console.error('获取热门帖子失败:', error)
    ElMessage.error('获取热门帖子失败')
  }
}

// 图片加载处理
const handleImageLoad = (imageUrl) => {
  if (imageUrl) {
    imageLoadingStates.value[imageUrl] = false
  }
}

// 图片加载错误处理
const handleImageError = (imageUrl) => {
  if (imageUrl) {
    imageLoadingStates.value[imageUrl] = false
  }
}

// 头像加载处理
const handleAvatarLoad = (avatarUrl) => {
  if (avatarUrl) {
    avatarLoadingStates.value[avatarUrl] = false
  }
}

// 头像加载错误处理
const handleAvatarError = (event) => {
  const src = event.target.src
  if (src) {
    avatarLoadingStates.value[src] = false
  }
  event.target.src = defaultAvatar
}

// 打开图片查看器
const openImageModal = (imageUrl, index) => {
  currentImageSrc.value = imageUrl.startsWith('http') ? imageUrl : 'http://localhost:8080' + imageUrl
  currentImageIndex.value = index
  showImageModal.value = true
  document.body.style.overflow = 'hidden'
}

// 关闭图片查看器
const closeImageModal = () => {
  showImageModal.value = false
  document.body.style.overflow = ''
}

// 切换到下一张图片
const nextImage = () => {
  if (currentImageIndex.value < postImages.value.length - 1) {
    currentImageIndex.value++
    const imageUrl = postImages.value[currentImageIndex.value].imageUrl
    currentImageSrc.value = imageUrl.startsWith('http') ? imageUrl : 'http://localhost:8080' + imageUrl
  }
}

// 切换到上一张图片
const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--
    const imageUrl = postImages.value[currentImageIndex.value].imageUrl
    currentImageSrc.value = imageUrl.startsWith('http') ? imageUrl : 'http://localhost:8080' + imageUrl
  }
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (!showImageModal.value) return
  
  switch (event.key) {
    case 'ArrowLeft':
      prevImage()
      break
    case 'ArrowRight':
      nextImage()
      break
    case 'Escape':
      closeImageModal()
      break
  }
}

// 添加键盘事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

// 移除键盘事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化相对时间
const formatRelativeTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now - date
  const diffMins = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffMins < 1) return '刚刚'
  if (diffMins < 60) return `${diffMins}分钟前`
  if (diffHours < 24) return `${diffHours}小时前`
  if (diffDays < 7) return `${diffDays}天前`
  return formatDate(dateString)
}

// 获取状态标签样式
const getStatusBadgeClass = (status) => {
  const statusClasses = {
    'approved': 'bg-success',
    'pending': 'bg-warning text-dark',
    'rejected': 'bg-danger'
  }
  return statusClasses[status] || 'bg-secondary'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusTexts = {
    'approved': '已审核',
    'pending': '待审核',
    'rejected': '已拒绝'
  }
  return statusTexts[status] || '未知'
}

//检查是否关注了指定用户
const checkIfFollowing = (followingList, targetUserId) => {
  if (!Array.isArray(followingList) || !targetUserId) {
    return false
  }
  
  // 确保我们在followingList中查找具有followingId等于targetUserId的项
  return followingList.some(item => {
    return item.followingId === targetUserId
  })
}

//根据userId和postId获取likes表id
const getLikesId = async (userId, postId) => {
  try {
    const res = await getLikesIdService(userId, postId)
    
    // 处理不同的返回情况
    if (!res.data) {
      // 返回为空的情况
      return { likeId: null, favoriteId: null };
    }
    
    if (Array.isArray(res.data)) {
      // 返回多个对象的情况
      const likeItem = res.data.find(item => item.type === 'like');
      const favoriteItem = res.data.find(item => item.type === 'favorite');
      return { 
        likeId: likeItem ? likeItem.id : null, 
        favoriteId: favoriteItem ? favoriteItem.id : null 
      };
    } else {
      // 返回单个对象的情况
      if (res.data.type === 'like') {
        return { likeId: res.data.id, favoriteId: null };
      } else if (res.data.type === 'favorite') {
        return { likeId: null, favoriteId: res.data.id };
      } else {
        return { likeId: null, favoriteId: null };
      }
    }
  } catch (error) {
    console.error('获取点赞/收藏ID失败:', error);
    return { likeId: null, favoriteId: null };
  }
}

// 点赞/取消点赞帖子
const toggleLike = async () => {
  const userId = currentUser.value.id
  const postId = route.params.id
  
  try {
    const { likeId } = await getLikesId(userId, postId);
    
    if (post.value.isLiked) {
      // 取消点赞
      if (likeId) {
        await removeLikeService(likeId)
      }
      post.value.isLiked = false
      post.value.likeCount--
    } else {
      // 点赞
      await addLikeService({
        userId: userId,
        postId: postId,
        type: 'like'
      })
      post.value.isLiked = true
      post.value.likeCount++
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 收藏/取消收藏帖子
const toggleFavorite = async () => {
  const userId = currentUser.value.id
  const postId = route.params.id
  
  try {
    const { favoriteId } = await getLikesId(userId, postId);
    
    if (post.value.isFavorited) {
      // 取消收藏
      if (favoriteId) {
        await removeFavoriteService(favoriteId)
      }
      post.value.isFavorited = false
      post.value.favoriteCount--
    } else {
      // 收藏
      await addFavoriteService({
        userId: userId,
        postId: postId,
        type: 'favorite'
      })
      post.value.isFavorited = true
      post.value.favoriteCount++
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 关注/取消关注作者
const followAuthor = async () => {
  // 检查用户是否已登录
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.warning('请先登录后再进行关注操作')
    router.push('/login')
    return
  }
  
  // 检查是否有有效的作者ID
  if (!post.value.userId) {
    ElMessage.error('无法获取作者信息，无法执行关注操作')
    return
  }
  
  // 防止重复点击
  if (followLoading.value) return
  followLoading.value = true
  
  // 保存操作前的状态
  const wasFollowing = post.value.authorIsFollowed
  
  try {
    console.log('开始关注操作:', {
      currentUserId: currentUser.value.id,
      targetUserId: post.value.userId,
      isCurrentlyFollowed: post.value.authorIsFollowed
    })
    
    if (post.value.authorIsFollowed) {
      // 取消关注
      const res = await UnfollowService(post.value.userId)
      console.log('取消关注结果:', res)
      post.value.authorIsFollowed = false
      // 更新粉丝数
      post.value.authorFollowerCount = Math.max(0, (post.value.authorFollowerCount || 1) - 1)
      ElMessage.success('已取消关注')
    } else {
      // 关注用户
      const res = await FollowService(post.value.userId)
      console.log('关注结果:', res)
      post.value.authorIsFollowed = true
      // 更新粉丝数
      post.value.authorFollowerCount = (post.value.authorFollowerCount || 0) + 1
      ElMessage.success('关注成功')
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.response?.status,
      data: error.response?.data
    })
    
    // 出现错误时恢复原来的状态
    post.value.authorIsFollowed = wasFollowing
    
    // 根据错误状态码提供更友好的提示
    if (error.response?.status === 401) {
      ElMessage.error('请先登录后再进行关注操作')
      router.push('/login')
    } else if (error.response?.status === 400) {
      ElMessage.error('参数错误，无法执行关注操作')
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请稍后再试')
    } else {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message || '未知错误'))
    }
  } finally {
    // 无论成功与否，都重新检查关注状态以确保准确性
    try {
      const currentUserFollowingRes = await getFollowingListService(currentUser.value.id)
      const followingList = currentUserFollowingRes.data || []
      const newFollowStatus = checkIfFollowing(followingList, post.value.userId)
      post.value.authorIsFollowed = newFollowStatus
      console.log('操作后重新确认关注状态:', post.value.authorIsFollowed)
    } catch (checkError) {
      console.warn('重新检查关注状态失败:', checkError)
      post.value.authorIsFollowed = false
    }
    
    followLoading.value = false
  }
}

// 滚动到评论区
const scrollToComments = () => {
  document.getElementById('comments').scrollIntoView({ behavior: 'smooth' })
}

// 点赞/取消点赞评论
const toggleCommentLike = async (comment) => {
  try {
    // 先更新界面状态
    comment.isLiked = !comment.isLiked;
    
    // 更新点赞数
    if (comment.isLiked) {
      comment.likeCount = (comment.likeCount || 0) + 1;
    } else {
      comment.likeCount = Math.max(0, (comment.likeCount || 1) - 1);
    }
    
    // 发送请求到后端
    await likeCommentService(comment.id);
    
    // 显示对应的操作成功消息
    if (comment.isLiked) {
      ElMessage.success('点赞成功');
    } else {
      ElMessage.success('已取消点赞');
    }
  } catch (error) {
    // 如果操作失败，恢复原来的点赞状态
    comment.isLiked = !comment.isLiked;
    if (comment.isLiked) {
      comment.likeCount = (comment.likeCount || 0) + 1;
    } else {
      comment.likeCount = Math.max(0, (comment.likeCount || 1) - 1);
    }
    console.error('点赞评论失败:', error);
    ElMessage.error('点赞操作失败: ' + (error.response?.data?.message || error.message));
  }
}

// 回复评论
const replyToComment = (comment) => {
  replyToCommentId.value = comment.id
  newComment.value = `@${comment.userName} `
  scrollToComments()
}

// 取消回复
const cancelReply = () => {
  replyToCommentId.value = null
  newComment.value = ''
}

// 添加新评论
const addComment = async () => {
  if (!newComment.value.trim()) return
  
  // 检查用户是否已登录
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.warning('请先登录后再发表评论')
    router.push('/login')
    return
  }
  
  try {
    const commentData = {
      postId: parseInt(route.params.id),
      userId: currentUser.value.id,
      content: newComment.value,
      parentId: replyToCommentId.value || 0 // 如果是回复评论，则设置parentId
    }
    
    await addCommentService(commentData)
    
    // 重新获取评论
    await fetchComments(route.params.id)
    
    // 清空输入框和回复状态
    newComment.value = ''
    replyToCommentId.value = null
    
    ElMessage.success('评论发表成功')
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除评论
const deleteComment = async (comment) => {
  // 检查用户是否已登录
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.warning('请先登录后再进行删除操作')
    router.push('/login')
    return
  }
  
  // 检查是否是自己的评论
  if (comment.userId !== currentUser.value.id) {
    ElMessage.error('只能删除自己的评论')
    return
  }
  
  try {
    // 使用 Element Plus 的 MessageBox 确认删除操作
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deleteCommentService(comment.id)
    
    // 重新获取评论
    await fetchComments(route.params.id)
    
    ElMessage.success('评论删除成功')
  } catch (error) {
    // 如果用户点击取消按钮，error 会是 'cancel'，我们不需要显示错误消息
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 初始化数据
onMounted(() => {
  fetchPost()//帖子数据
  fetchRecommendedPosts()//热门推荐
  // 页面初始化时不需要调用getLikesId，因为会在需要时（如点击点赞/收藏按钮）调用
})

// 监听路由参数变化，当帖子ID改变时重新获取数据
watch(() => route.params.id, (newId, oldId) => {
  if (newId !== oldId) {
    fetchPost()
    fetchRecommendedPosts()
  }
})
</script>

<style scoped>
.post-detail-container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* 返回按钮样式 */
.back-button-container {
  padding: 1rem 0;
  margin-bottom: 1rem;
}

.btn-back {
  background: #fff;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.btn-back:hover {
  background: var(--primary-color);
  color: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
}

.btn-back:active {
  transform: translateY(0);
}

.post-content-card {
  border: none;
  border-radius: 12px;
}

.post-title {
  font-size: 1.8rem;
  font-weight: 700;
  line-height: 1.3;
  color: #333;
}

.post-meta {
  padding-bottom: 1rem;
  border-bottom: 1px solid #e9ecef;
}

.post-body {
  line-height: 1.7;
  font-size: 1.05rem;
}

.post-body .content {
  white-space: pre-line;
}

.post-actions .btn {
  border-radius: 20px;
  padding: 0.5rem 1.2rem;
}

.author-card {
  border: none;
  border-radius: 12px;
}

.author-card .card-header {
  border-radius: 12px 12px 0 0 !important;
}

.author-avatar img {
  border: 3px solid #e9ecef;
  transition: all 0.3s ease;
  cursor: pointer;
}

.author-avatar img:hover {
  transform: scale(1.1) rotate(5deg);
  border-color: #0d6efd;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}

.author-name {
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.author-stats .stat-item {
  text-align: center;
}

.stat-value {
  font-size: 1.2rem;
  font-weight: 600;
}

.stat-label {
  font-size: 0.8rem;
  color: #6c757d;
}

.recommended-posts-card {
  border: none;
  border-radius: 12px;
}

.recommended-post-item:last-child {
  border-bottom: none !important;
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
}

.recommended-post-item .post-title {
  font-size: 0.95rem;
  margin-bottom: 0.3rem;
}

.recommended-post-item .post-title a {
  text-decoration: none;
  color: #333;
}

.recommended-post-item .post-title a:hover {
  color: #0d6efd;
}

.comment-form textarea {
  resize: none;
  border-radius: 10px;
}

.comment-item {
  padding-bottom: 1rem;
}

.reply-item {
  background-color: #f8f9fa;
  padding: 0.5rem;
  border-radius: 5px;
}

.comment-actions .btn {
  font-size: 0.8rem;
  padding: 0.2rem 0.6rem;
}

.breadcrumb {
  background-color: transparent;
  padding: 0;
}

.breadcrumb-item a {
  text-decoration: none;
  color: #6c757d;
}

.breadcrumb-item a:hover {
  color: #0d6efd;
}

.breadcrumb-item.active {
  color: #495057;
}

/* 自定义轮播控制按钮样式 */
.custom-carousel-control {
  width: 50px;
  height: 50px;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(13, 110, 253, 0.7); /* 蓝色背景，带透明度 */
  border-radius: 50%;
  border: none;
  opacity: 1;
  transition: all 0.3s ease;
}

.custom-carousel-control:hover {
  background-color: rgba(13, 110, 253, 0.9); /* 悬停时更深的蓝色 */
  width: 55px;
  height: 55px;
}

.custom-carousel-control.prev {
  left: 15px;
}

.custom-carousel-control.next {
  right: 15px;
}

.custom-carousel-icon {
  background-image: none;
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-carousel-icon::before {
  content: "";
  display: block;
  width: 12px;
  height: 12px;
  border-top: 2px solid white;
  border-left: 2px solid white;
}

.carousel-control-prev .custom-carousel-icon::before {
  transform: rotate(-45deg);
  margin-right: 2px;
}

.carousel-control-next .custom-carousel-icon::before {
  transform: rotate(135deg);
  margin-left: 2px;
}

.carousel-indicators [data-bs-target] {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: rgba(13, 110, 253, 0.5);
  border: none;
}

.carousel-indicators .active {
  background-color: #0d6efd;
}

/* 图片放大查看器样式 */
.image-modal {
  display: block;
  position: fixed;
  z-index: 10000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.9);
}

.image-modal-content {
  display: block;
  margin: auto;
  max-width: 90%;
  max-height: 90%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.image-modal-image {
  max-width: 100%;
  max-height: 80vh;
  display: block;
  margin: auto;
}

.image-modal-close {
  position: absolute;
  top: 30px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  cursor: pointer;
  z-index: 10001;
}

.image-modal-close:hover,
.image-modal-close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

.image-modal-caption {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: #f1f1f1;
  font-size: 18px;
  text-align: center;
  width: 100%;
}

/* 图片查看器导航按钮 */
.image-modal-nav {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  font-size: 30px;
  cursor: pointer;
  z-index: 10002;
  padding: 15px;
  user-select: none;
}

.image-modal-nav-prev {
  left: 20px;
}

.image-modal-nav-next {
  right: 20px;
}

.image-modal-nav:hover {
  color: #ccc;
}

@media (max-width: 768px) {
  .post-title {
    font-size: 1.5rem;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .post-status {
    margin-top: 0.5rem;
  }
  
  .post-actions .action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }
  
  .post-actions .btn {
    flex: 1;
    min-width: 120px;
  }
  
  .custom-carousel-control {
    width: 40px;
    height: 40px;
  }
  
  .custom-carousel-control:hover {
    width: 45px;
    height: 45px;
  }
}
</style>